package com.chutoutian.interceptor;

import com.alibaba.fastjson.JSON;
import com.chutoutian.common.Code;
import com.chutoutian.po.User;
import com.chutoutian.vo.ResponseMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            if (isAjax(request)) {
                ResponseMessage responseMessage = new ResponseMessage.Builder().code(Code.CODE_500).message("未登錄").bulid();
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(responseMessage));
                response.getWriter().flush();
            } else {
                response.sendRedirect(request.getContextPath() + "/content/login/index.html");
            }
            return false;
        }
        return true;
    }

    public boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null &&
                "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }
}
